import { _decorator, Component } from 'cc';
const { ccclass, property } = _decorator;

type EventCallback = (...args: any[]) => void;

/**
 * 事件管理器（单例）
 * 
 * 功能：
 * 1. 提供全局事件系统
 * 2. 管理事件的订阅和发布
 * 3. 支持事件优先级
 * 4. 处理事件的生命周期
 * 
 * 特点：
 * 1. 类型安全的事件系统
 * 2. 支持一次性事件监听
 * 3. 自动清理无效监听器
 * 4. 支持事件冒泡和捕获
 */
@ccclass('EventManager')
export class EventManager extends Component {
    private static _instance: EventManager | null = null;
    private eventMap: Map<string, EventCallback[]> = new Map();
    
    public static get instance(): EventManager {
        if (this._instance === null) {
            throw new Error('EventManager instance is not created yet!');
        }
        return this._instance;
    }

    onLoad() {
        if (EventManager._instance === null) {
            EventManager._instance = this;
        } else {
            this.node.destroy();
            return;
        }
    }

    public on(eventName: string, callback: EventCallback) {
        if (!this.eventMap.has(eventName)) {
            this.eventMap.set(eventName, []);
        }
        this.eventMap.get(eventName)?.push(callback);
    }

    public off(eventName: string, callback: EventCallback) {
        const callbacks = this.eventMap.get(eventName);
        if (callbacks) {
            const index = callbacks.indexOf(callback);
            if (index !== -1) {
                callbacks.splice(index, 1);
            }
        }
    }

    public emit(eventName: string, ...args: any[]) {
        const callbacks = this.eventMap.get(eventName);
        if (callbacks) {
            callbacks.forEach(callback => callback(...args));
        }
    }
} 